import { WS_CONFIG } from '@/config/websocket';

class WebSocketClient {
    constructor() {
        this.ws = null;
        
        this.reconnectAttempts = 0;
        this.maxReconnectAttempts = WS_CONFIG.RECONNECT.MAX_ATTEMPTS;
        this.reconnectInterval = WS_CONFIG.RECONNECT.INTERVAL;
        this.messageHandlers = new Map();
        this.isConnected = false;
        this.heartbeatInterval = null;
        this.heartbeatTimeout = null;
        this.connectionTimeout = null;
        this.debug = WS_CONFIG.DEBUG;
        this.soundsEnabled = WS_CONFIG.SOUNDS.ENABLED;
        
        // 保存会话ID便于消息发送
        this.sessionId = null;
        // 是否正在尝试连接
        this.connecting = false;
        // 是否正在等待心跳响应
        this.waitingForPong = false;
        // 连接锁，防止多处同时发起连接
        this.connectionLock = false;
        // 上次连接时间
        this.lastConnectTime = 0;
        // 最小重连间隔(毫秒)
        this.minReconnectInterval = 5000;
        // 音频对象
        this.sounds = {
            messageReceived: null,
            messageSent: null,
            notification: null,
            click: null,
            welcome: null,
            alert: null
        };
        
        // 添加用户交互标志
        this.userInteracted = false;
        
        // 检测用户交互
        if (typeof document !== 'undefined') {
            document.addEventListener('click', () => {
                this.userInteracted = true;
            });
            document.addEventListener('touchstart', () => {
                this.userInteracted = true;
            });
            document.addEventListener('keydown', () => {
                this.userInteracted = true;
            });
        }
        
        // 初始化音频
        this.initSounds();
    }
    
    // 初始化音频对象
    initSounds() {
        if (this.soundsEnabled) {
            try {
                this.sounds.messageReceived = uni.createInnerAudioContext();
                this.sounds.messageReceived.src = WS_CONFIG.SOUNDS.MESSAGE_RECEIVED;
                this.sounds.messageReceived.preload = true;
                
                this.sounds.messageSent = uni.createInnerAudioContext();
                this.sounds.messageSent.src = WS_CONFIG.SOUNDS.MESSAGE_SENT;
                this.sounds.messageSent.preload = true;
                
                this.sounds.notification = uni.createInnerAudioContext();
                this.sounds.notification.src = WS_CONFIG.SOUNDS.NOTIFICATION;
                this.sounds.notification.preload = true;
                
                this.sounds.click = uni.createInnerAudioContext();
                this.sounds.click.src = WS_CONFIG.SOUNDS.CLICK;
                this.sounds.click.preload = true;
                
                this.sounds.welcome = uni.createInnerAudioContext();
                this.sounds.welcome.src = WS_CONFIG.SOUNDS.WELCOME;
                this.sounds.welcome.preload = true;
                
                this.sounds.alert = uni.createInnerAudioContext();
                this.sounds.alert.src = WS_CONFIG.SOUNDS.ALERT;
                this.sounds.alert.preload = true;
                
                this.log('音频初始化成功');
            } catch (error) {
                this.error('音频初始化失败:', error);
                this.soundsEnabled = false;
            }
        }
    }
    
    // 播放声音
    playSound(type) {
        if (!this.soundsEnabled) return;
        
        // 如果用户尚未与页面交互且不在App环境中，则不播放声音
        // #ifdef H5
        if (!this.userInteracted) {
            this.log('用户尚未与页面交互，跳过声音播放');
            return;
        }
        // #endif
        
        try {
            let sound;
            switch (type) {
                case 'received':
                    sound = this.sounds.messageReceived;
                    break;
                case 'sent':
                    sound = this.sounds.messageSent;
                    break;
                case 'notification':
                    sound = this.sounds.notification;
                    break;
                case 'click':
                    sound = this.sounds.click;
                    break;
                case 'welcome':
                    sound = this.sounds.welcome;
                    break;
                case 'alert':
                    sound = this.sounds.alert;
                    break;
                default:
                    sound = this.sounds.messageSent;
            }
            
            if (sound) {
                // 先停止之前的播放，避免重叠
                try {
                    sound.stop();
                } catch (e) {
                    // 忽略停止错误
                }
                
                // 重置播放位置
                try {
                    sound.seek(0);
                } catch (e) {
                    // 忽略seek错误
                }
                
                // 使用setTimeout延迟播放，避免连续多次播放导致的错误
                setTimeout(() => {
                    try {
                        sound.play();
                    } catch (e) {
                        this.error('播放声音失败:', e);
                    }
                }, WS_CONFIG.SOUNDS.DELAY || 50);
            }
        } catch (error) {
            this.error('播放声音失败:', error);
        }
    }

    connect(userId) {
        if (!userId) {
            this.error('WebSocket连接失败：用户ID不能为空');
            return Promise.reject(new Error('用户ID不能为空'));
        }

        // 如果已经连接或正在连接中，直接返回
        if (this.connecting) {
            this.log('WebSocket正在连接中，请勿重复连接');
            return Promise.reject(new Error('正在连接中'));
        }

        if (this.ws && this.isConnected) {
            this.log('WebSocket已连接');
            return Promise.resolve();
        }

        // 检查连接锁，防止多处同时发起连接
        if (this.connectionLock) {
            this.log('WebSocket连接被锁定，请等待上一次连接完成');
            return Promise.reject(new Error('连接被锁定'));
        }
        
        // 检查最小重连间隔
        const now = Date.now();
        if (now - this.lastConnectTime < this.minReconnectInterval) {
            this.log(`WebSocket连接过于频繁，请等待${Math.ceil((this.lastConnectTime + this.minReconnectInterval - now) / 1000)}秒后重试`);
            return Promise.reject(new Error('连接过于频繁'));
        }
        
        // 更新上次连接时间
        this.lastConnectTime = now;
        
        // 设置连接锁
        this.connectionLock = true;
        
        // 清理之前可能存在的连接
        if (this.ws) {
            try {
                this.ws.close();
                this.ws = null;
            } catch (e) {
                this.error('关闭旧WebSocket连接失败:', e);
            }
        }
        
        this.connecting = true;
        
        // 清除之前的超时计时器
        if (this.connectionTimeout) {
            clearTimeout(this.connectionTimeout);
        }
        
        return new Promise((resolve, reject) => {
            // 设置连接超时
            this.connectionTimeout = setTimeout(() => {
                if (this.connecting && !this.isConnected) {
                    this.error('WebSocket连接超时');
                    this.connecting = false;
                    this.connectionLock = false;
                    
                    // 如果WebSocket对象存在，尝试关闭
                    if (this.ws) {
                        try {
                            this.ws.close();
                        } catch (e) {
                            this.error('关闭超时连接失败:', e);
                        }
                        this.ws = null;
                    }
                    
                    reject(new Error('连接超时'));
                    
                    // 触发连接失败事件
                    uni.$emit('websocket-timeout', {
                        userId: userId,
                        timestamp: new Date().toISOString()
                    });
                }
            }, WS_CONFIG.CONNECTION.TIMEOUT);
            
            // 创建正确的WebSocket URL，包含token
            const token = uni.getStorageSync('token');
            if (!token) {
                this.error('WebSocket连接失败：未找到token');
                this.connecting = false;
                this.connectionLock = false;
                clearTimeout(this.connectionTimeout);
                return reject(new Error('未找到token'));
            }
            
            const tokenWithPrefix = token.startsWith('Bearer ') ? token : `Bearer ${token}`;
            const wsUrl = `${WS_CONFIG.WS_URL}/${userId}?token=${encodeURIComponent(tokenWithPrefix)}`;
            this.log('正在连接WebSocket:', wsUrl);

            try {
                // 使用uni-app WebSocket API
                this.ws = uni.connectSocket({
                    url: wsUrl,
                    success: () => {
                        this.log('WebSocket连接请求已发送');
                    },
                    fail: (error) => {
                        this.error('WebSocket连接请求失败:', error);
                        this.connecting = false;
                        this.connectionLock = false;
                        clearTimeout(this.connectionTimeout);
                        reject(error);
                    }
                });
                
                // 设置事件处理程序
                this.ws.onOpen(() => {
                    this.log('WebSocket连接已建立');
                    this.isConnected = true;
                    this.connecting = false;
                    this.connectionLock = false;
                    this.reconnectAttempts = 0;
                    
                    // 清除连接超时
                    clearTimeout(this.connectionTimeout);
                    
                    // 开始心跳检测
                    this.startHeartbeat();
                    
                    resolve();
                    
                    // 发送连接成功事件
                    uni.$emit('websocket-connected', {
                        userId: userId,
                        timestamp: new Date().toISOString()
                    });
                    
                    // 播放连接成功音效
                    this.playSound('sent');
                });

                this.ws.onClose((event) => {
                    this.log('WebSocket连接已关闭', event);
                    this.isConnected = false;
                    this.connecting = false;
                    this.connectionLock = false;
                    this.stopHeartbeat();
                    
                    // 清除连接超时
                    clearTimeout(this.connectionTimeout);
                    
                    // 发送连接断开事件
                    uni.$emit('websocket-disconnected', {
                        userId: userId,
                        timestamp: new Date().toISOString(),
                        code: event.code,
                        reason: event.reason
                    });
                    
                    // 尝试重新连接
                    this.handleReconnect(userId);
                });

                this.ws.onError((error) => {
                    this.error('WebSocket错误:', error);
                    this.isConnected = false;
                    this.connecting = false;
                    this.connectionLock = false;
                    
                    // 清除连接超时
                    clearTimeout(this.connectionTimeout);
                    
                    // 发送错误事件
                    uni.$emit('websocket-error', {
                        error: error,
                        timestamp: new Date().toISOString()
                    });
                    
                    // 显示错误消息，但不打断用户操作
                    uni.showToast({
                        title: '连接服务器失败，正在重试...',
                        icon: 'none',
                        duration: 2000
                    });
                    
                    reject(error);
                    
                    // 尝试重新连接
                    this.handleReconnect(userId);
                });

                this.ws.onMessage((event) => {
                    try {
                        let message;
                        
                        // 尝试解析消息数据
                        if (typeof event.data === 'string') {
                            try {
                                message = JSON.parse(event.data);
                            } catch (parseError) {
                                this.error('消息数据解析失败:', parseError, event.data);
                                
                                // 检查是否包含JSON格式的消息体
                                const match = event.data.match(/{.*}/);
                                if (match) {
                                    try {
                                        message = JSON.parse(match[0]);
                                    } catch (innerError) {
                                        this.error('提取的JSON解析失败:', innerError);
                                    }
                                }
                                
                                // 如果仍然无法解析，使用原始消息
                                if (!message) {
                                    message = {
                                        type: 'ERROR',
                                        content: '消息格式错误',
                                        timestamp: new Date().toISOString(),
                                        status: 'ERROR'
                                    };
                                }
                            }
                        } else if (event.data && typeof event.data === 'object') {
                            message = event.data;
                        } else {
                            this.error('未知的消息格式:', event);
                            message = {
                                type: 'ERROR',
                                content: '未知的消息格式',
                                timestamp: new Date().toISOString(),
                                status: 'ERROR'
                            };
                        }
                        
                        // 确保消息有状态字段
                        if (!message.status) {
                            message.status = 'SENT';
                        }
                        
                        // 确保消息有正确格式的时间戳
                        if (!message.timestamp) {
                            message.timestamp = new Date().toISOString();
                        } else if (message.timestamp instanceof Date) {
                            message.timestamp = message.timestamp.toISOString();
                        }
                        
                        // 处理心跳响应
                        if (message.type === 'PONG') {
                            this.log('收到心跳响应');
                            // 重置心跳等待标志
                            this.waitingForPong = false;
                            // 清除心跳超时
                            if (this.heartbeatTimeout) {
                                clearTimeout(this.heartbeatTimeout);
                                this.heartbeatTimeout = null;
                            }
                            return;
                        }
                        
                        this.log('收到消息:', message);
                        
                        // 播放接收消息音效（仅对聊天消息）
                        if (message.type === 'CHAT') {
                            this.playSound('received');
                        } else if (message.type === 'SESSION_ASSIGNED' || message.type === 'PENDING_SESSIONS') {
                            // 对于新分配的会话或待处理会话，播放提示音
                            this.playSound('alert');
                        }
                        
                        // 发送接收到新消息的事件
                        uni.$emit('websocket-message', message);
                        
                        // 根据消息类型处理消息
                        this.handleMessage(message);
                    } catch (error) {
                        this.error('消息处理错误:', error, event.data);
                    }
                });
                
            } catch (error) {
                this.error('创建WebSocket连接失败:', error);
                this.connecting = false;
                this.connectionLock = false;
                clearTimeout(this.connectionTimeout);
                reject(error);
            }
        });
    }

    handleMessage(message) {
        // 根据消息类型找到对应的处理程序
        const handler = this.messageHandlers.get(message.type);
        if (handler) {
            handler(message);
        } else {
            this.log('无处理程序的消息类型:', message.type, message);
            
            // 默认的消息处理
            switch(message.type) {
                case 'CHAT':
                    uni.$emit('new-chat-message', message);
                    break;
                case 'SYSTEM':
                    uni.$emit('system-message', message);
                    break;
                case 'ERROR':
                    this.error('收到错误消息:', message);
                    uni.$emit('error-message', message);
                    uni.showToast({
                        title: message.content || '发生错误',
                        icon: 'none',
                        duration: 3000
                    });
                    break;
                case 'SESSION_REJECTED':
                    this.log('收到会话拒绝消息:', message);
                    uni.$emit('session-rejected', message);
                    break;
                case 'SESSION_ACCEPTED':
                    this.log('收到会话接受消息:', message);
                    uni.$emit('session-accepted', message);
                    break;
                case 'SESSION_ENDED':
                    this.log('收到会话结束消息:', message);
                    uni.$emit('session-ended', message);
                    break;
                case 'TRANSFER':
                    this.log('收到会话转接消息:', message);
                    uni.$emit('transfer-message', message);
                    break;
                case 'SESSION_ASSIGNED':
                    this.log('收到会话分配消息:', message);
                    uni.$emit('session-assigned', message);
                    break;
                default:
                    this.log('未处理的消息类型:', message.type, message);
                    // 尝试解析消息数据
                    if (typeof message.data === 'string') {
                        try {
                            const parsedData = JSON.parse(message.data);
                            this.log('解析消息数据:', parsedData);
                            
                            // 根据解析后的数据类型处理
                            if (parsedData.type) {
                                this.handleMessage(parsedData);
                            }
                        } catch (error) {
                            this.error('解析消息数据失败:', error);
                        }
                    }
                    break;
            }
        }
    }

    addMessageHandler(type, handler) {
        this.messageHandlers.set(type, handler);
        return this; // 支持链式调用
    }

    removeMessageHandler(type) {
        this.messageHandlers.delete(type);
        return this; // 支持链式调用
    }

    sendMessage(message, retryCount = 0) {
        if (!this.ws || !this.isConnected) {
            this.error('WebSocket未连接，无法发送消息');
            return Promise.reject(new Error('WebSocket未连接'));
        }

        // 确保消息格式正确
        if (typeof message === 'object') {
            // 添加必要的字段
            if (!message.timestamp) {
                message.timestamp = new Date().toISOString();
            } else if (message.timestamp instanceof Date) {
                message.timestamp = message.timestamp.toISOString();
            }
                
            // 确保消息有类型
            if (!message.type) {
                message.type = 'CHAT';
            }
            
            // 确保消息有状态
            if (!message.status) {
                message.status = 'SENT';
            }
            
            // 确保消息有发送者类型
            if (!message.senderType) {
                // 从存储中获取用户信息
                const userInfo = uni.getStorageSync('userInfo');
                message.senderType = userInfo?.userType === 'SERVICE' ? 'SERVICE' : 'USER';
            }
            
            // 确保CHAT类型消息有senderId
            if (message.type === 'CHAT' && !message.senderId) {
                const userInfo = uni.getStorageSync('userInfo');
                message.senderId = userInfo?.userId || userInfo?.id;
            }
            
            // 确保PING消息有sessionId字段，防止后端NPE
            if (message.type === 'PING' && !message.sessionId) {
                message.sessionId = this.sessionId || '';
            }
            
            // 如果是SESSION_REJECTED或SESSION_ACCEPTED类型的消息，确保有正确的格式
            if (message.type === 'SESSION_REJECTED' || message.type === 'SESSION_ACCEPTED') {
                // 确保有sessionId
                if (!message.sessionId) {
                    this.error('消息缺少sessionId字段');
                    return Promise.reject(new Error('消息格式错误：缺少sessionId字段'));
                }
                
                // 确保有serviceId
                if (!message.serviceId) {
                    this.error('消息缺少serviceId字段');
                    return Promise.reject(new Error('消息格式错误：缺少serviceId字段'));
                }
            }
        } else {
            this.error('消息必须是对象类型');
            return Promise.reject(new Error('消息格式错误：消息必须是对象类型'));
        }

        return new Promise((resolve, reject) => {
            try {
                const messageStr = JSON.stringify(message);
                this.log('发送消息:', message);
                
                this.ws.send({
                    data: messageStr,
                    success: () => {
                        this.log('消息发送成功');
                        
                        // 播放发送成功音效（仅对聊天消息）
                        if (message.type === 'CHAT') {
                            this.playSound('sent');
                        }
                        
                        resolve(true);
                    },
                    fail: (error) => {
                        this.error('消息发送失败:', error);
                        
                        // 尝试重新连接并重发消息
                        if (retryCount < 3) {
                            this.log(`消息发送失败，尝试重发 (${retryCount + 1}/3)`);
                            
                            // 如果连接已断开，先尝试重连
                            if (!this.isConnected) {
                                const userInfo = uni.getStorageSync('userInfo');
                                if (userInfo && userInfo.id) {
                                    this.connect(userInfo.id).then(() => {
                                        // 连接成功后重发消息
                                        setTimeout(() => {
                                            this.sendMessage(message, retryCount + 1)
                                                .then(resolve)
                                                .catch(reject);
                                        }, 500);
                                    }).catch(() => {
                                        reject(error);
                                    });
                                } else {
                                    reject(error);
                                }
                            } else {
                                // 连接正常，直接重发
                                setTimeout(() => {
                                    this.sendMessage(message, retryCount + 1)
                                        .then(resolve)
                                        .catch(reject);
                                }, 1000);
                            }
                        } else {
                            this.error('消息发送失败，已达到最大重试次数');
                            reject(error);
                        }
                    }
                });
            } catch (error) {
                this.error('发送消息时发生错误:', error);
                reject(error);
            }
        });
    }
    
    // 发送聊天消息的便捷方法
    sendChatMessage(content, sessionId, receiverId, messageType = 'TEXT') {
        // 从存储中获取用户信息
        const userInfo = uni.getStorageSync('userInfo');
        if (!userInfo || !userInfo.userId) {
            return Promise.reject(new Error('未找到用户信息'));
        }
        
        const message = {
            type: 'CHAT',
            sessionId: sessionId || this.sessionId,
            senderId: userInfo.userId,
            senderType: 'USER',
            receiverId: receiverId,
            content: content,
            messageType: messageType,
            timestamp: new Date().toISOString(),
            status: 'SENT'
        };
        
        return this.sendMessage(message);
    }

    handleReconnect(userId) {
        if (this.reconnectAttempts >= this.maxReconnectAttempts) {
            this.error('WebSocket重连次数超过最大限制');
            uni.showToast({
                title: '连接服务器失败，请刷新页面重试',
                icon: 'none',
                duration: 3000
            });
            
            // 触发重连失败事件
            uni.$emit('websocket-reconnect-failed', {
                userId: userId,
                timestamp: new Date().toISOString(),
                attempts: this.reconnectAttempts
            });
            
            return;
        }

        // 如果连接锁已激活，不要重连
        if (this.connectionLock) {
            this.log('连接锁已激活，取消重连');
            return;
        }

        // 如果正在连接中，不要重连
        if (this.connecting) {
            this.log('正在连接中，取消重连');
            return;
        }

        this.reconnectAttempts++;
        this.log(`尝试重新连接 (${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
        
        // 使用指数退避算法计算重连延迟
        const delay = Math.min(
            this.reconnectInterval * Math.pow(WS_CONFIG.RECONNECT.BACKOFF_RATE || 1.5, this.reconnectAttempts - 1),
            30000 // 最大30秒
        );

        this.log(`将在 ${delay/1000} 秒后重连`);

        setTimeout(() => {
            // 再次检查连接状态，避免重复连接
            if (this.isConnected) {
                this.log('已经连接，取消重连');
                return;
            }
            
            // 检查连接锁
            if (this.connectionLock) {
                this.log('连接锁已激活，取消重连');
                return;
            }
            
            // 检查是否正在连接中
            if (this.connecting) {
                this.log('正在连接中，取消重连');
                return;
            }
            
            if (userId) {
                this.connect(userId).catch(error => {
                    this.error('重连失败:', error);
                });
            } else {
                const userInfo = uni.getStorageSync('userInfo');
                if (userInfo && (userInfo.userId || userInfo.id)) {
                    this.connect(userInfo.userId || userInfo.id).catch(error => {
                        this.error('重连失败:', error);
                    });
                } else {
                    this.error('无法重连：未找到用户ID');
                }
            }
        }, delay);
    }

    startHeartbeat() {
        this.stopHeartbeat();
        
        // 心跳检测间隔
        this.heartbeatInterval = setInterval(() => {
            if (this.isConnected) {
                // 如果正在等待上一次心跳响应，说明连接可能已断开
                if (this.waitingForPong) {
                    this.error('上一次心跳未收到响应，可能连接已断开');
                    
                    // 尝试关闭连接并重连
                    try {
                        this.ws.close();
                    } catch (e) {
                        this.error('关闭无响应连接失败:', e);
                    }
                    
                    this.isConnected = false;
                    this.waitingForPong = false;
                    
                    // 获取用户ID并重连
                    const userInfo = uni.getStorageSync('userInfo');
                    if (userInfo && (userInfo.userId || userInfo.id)) {
                        this.handleReconnect(userInfo.userId || userInfo.id);
                    }
                    
                    return;
                }
                
                // 发送心跳并设置等待标志
                this.waitingForPong = true;
                
                this.sendMessage({
                    type: 'PING',
                    timestamp: new Date().toISOString(),
                    sessionId: this.sessionId || '', // 确保有sessionId字段
                    status: 'SENT'
                }).catch(error => {
                    this.error('发送心跳失败:', error);
                    this.waitingForPong = false;
                });
                
                // 设置心跳响应超时
                this.heartbeatTimeout = setTimeout(() => {
                    if (this.waitingForPong) {
                        this.error('心跳响应超时');
                        this.waitingForPong = false;
                        
                        // 记录心跳失败次数
                        this.heartbeatFailCount = (this.heartbeatFailCount || 0) + 1;
                        
                        // 如果超过最大重试次数，关闭连接并重连
                        if (this.heartbeatFailCount >= (WS_CONFIG.HEARTBEAT.RETRY_LIMIT || 2)) {
                            this.error(`心跳失败次数(${this.heartbeatFailCount})超过限制，重新连接`);
                            
                            // 尝试关闭连接并重连
                            try {
                                this.ws.close();
                            } catch (e) {
                                this.error('关闭无响应连接失败:', e);
                            }
                            
                            this.isConnected = false;
                            this.heartbeatFailCount = 0;
                            
                            // 获取用户ID并重连
                            const userInfo = uni.getStorageSync('userInfo');
                            if (userInfo && (userInfo.userId || userInfo.id)) {
                                this.handleReconnect(userInfo.userId || userInfo.id);
                            }
                        } else {
                            this.log(`心跳失败(${this.heartbeatFailCount}/${WS_CONFIG.HEARTBEAT.RETRY_LIMIT || 2})，继续尝试`);
                        }
                    }
                }, WS_CONFIG.HEARTBEAT.TIMEOUT);
            }
        }, WS_CONFIG.HEARTBEAT.INTERVAL);
    }

    stopHeartbeat() {
        // 清除心跳检测定时器
        if (this.heartbeatInterval) {
            clearInterval(this.heartbeatInterval);
            this.heartbeatInterval = null;
        }
        
        // 清除心跳响应超时定时器
        if (this.heartbeatTimeout) {
            clearTimeout(this.heartbeatTimeout);
            this.heartbeatTimeout = null;
        }
        
        // 重置等待标志和失败计数
        this.waitingForPong = false;
        this.heartbeatFailCount = 0;
    }

    disconnect() {
        this.stopHeartbeat();
        
        // 清除连接超时
        if (this.connectionTimeout) {
            clearTimeout(this.connectionTimeout);
            this.connectionTimeout = null;
        }
        
        if (this.ws) {
            try {
            this.ws.close();
            } catch (e) {
                this.error('关闭WebSocket连接失败:', e);
            }
            this.ws = null;
        }
        
        this.isConnected = false;
        this.connecting = false;
        this.messageHandlers.clear();
        this.sessionId = null;
        this.reconnectAttempts = 0;
        
        // 释放音频资源
        if (this.sounds.messageReceived) {
            try {
                this.sounds.messageReceived.destroy();
            } catch (e) {
                // 忽略销毁错误
            }
        }
        if (this.sounds.messageSent) {
            try {
                this.sounds.messageSent.destroy();
            } catch (e) {
                // 忽略销毁错误
            }
        }
        if (this.sounds.notification) {
            try {
                this.sounds.notification.destroy();
            } catch (e) {
                // 忽略销毁错误
            }
        }
        if (this.sounds.click) {
            try {
                this.sounds.click.destroy();
            } catch (e) {
                // 忽略销毁错误
            }
        }
        if (this.sounds.welcome) {
            try {
                this.sounds.welcome.destroy();
            } catch (e) {
                // 忽略销毁错误
            }
        }
        if (this.sounds.alert) {
            try {
                this.sounds.alert.destroy();
            } catch (e) {
                // 忽略销毁错误
            }
        }
    }
    
    // 设置当前会话ID
    setSessionId(sessionId) {
        this.sessionId = sessionId;
        return this;
    }
    
    // 启用/禁用声音
    setSoundsEnabled(enabled) {
        this.soundsEnabled = enabled;
        return this;
    }
    
    // 获取声音启用状态
    isSoundsEnabled() {
        return this.soundsEnabled;
    }
    
    log(...args) {
        if (this.debug) {
            console.log('[WebSocket]', ...args);
        }
    }
    
    error(...args) {
        console.error('[WebSocket Error]', ...args);
    }
    
    // 设置用户已交互状态
    setUserInteracted(value = true) {
        this.userInteracted = value;
    }
    
    // 获取用户交互状态
    getUserInteracted() {
        return this.userInteracted;
    }
}

export default new WebSocketClient(); 